<template>
  <!-- :model="form" -->
  <el-form label-width="100px">
    <el-form-item label="SPU名称">
      <el-input type="text" placeholder="SPU名称" v-model="spuForm.spuName"></el-input>
    </el-form-item>
    <el-form-item label="品牌">
      <el-select placeholder="请选择" v-model="spuForm.tmId" >
        <el-option
          v-for="tm in trademarkList"
          :key="tm.id"
          :value="(tm.id as number)"
          :label="tm.tmName"
        ></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="SPU描述">
      <el-input type="textarea" :rows="3" placeholder="SPU描述" v-model="spuForm.description"></el-input>
    </el-form-item>
    <el-form-item label="SPU图片">
      <el-upload
         v-model:file-list="(spuImageList as any)"
        action="/app-dev/admin/product/upload"
        list-type="picture-card"
        :on-success="handlerSuccess"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove"
      >
        <el-icon><Plus /></el-icon>
      </el-upload>

      <el-dialog v-model="dialogVisible">
        <img w-full :src="dialogImageUrl" style="width:100%;" />
      </el-dialog>
    </el-form-item>

    <el-form-item label="销售属性">
      <div class="mb-10">
        <el-select :placeholder="`还有 ${saleAttrList?.length}  个未选择`" class="mr-10" v-model="attrIdAttrVal">
        <!-- v-for="bsa in baseSaleAttrList" -->
          <el-option
            v-for="bsa in saleAttrList"
            :key="bsa.id"
            :value="`${bsa.id}:${bsa.name}`"
            :label="bsa.name"
          ></el-option>
        </el-select>
        <el-button type="primary"  @click="addSaleAttr">添加销售属性</el-button>
      </div>
      <el-table :data="spuForm.spuSaleAttrList" border>
        <el-table-column type="index" label="序号" align="center" width="80" />
        <el-table-column label="属性名" width="200" prop="saleAttrName"/>
        <el-table-column label="属性值名称列表">
          <template #default="{row,$index}">
            <el-tag 
              closable
              @close="row.spuSaleAttrValueList.splice($index,1)"
              v-for="saleAttrVal in row.spuSaleAttrValueList"
            class='mr-10'
            >
            {{saleAttrVal.saleAttrValueName}}
            </el-tag>
             <el-input
                v-if="row.inputVisible"
                ref="InputRef"
                v-model="row.inputValue"
                class="w-50"
                size="small"
                @keyup.enter="handleInputConfirm(row)"
                @blur="handleInputConfirm(row)"
              />
            <el-button v-else class="button-new-tag ml-1" size="small" @click="showInput(row)">
              新增
            </el-button>
         </template>
        </el-table-column>
        <el-table-column label="操作" width="80">
          <template #default="{ row, $index }">
            <el-button type="danger" :icon="Delete" @click="spuForm.spuSaleAttrList.splice($index, 1)"></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="onSave">保存</el-button>
      <el-button @click="cancelSave">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { Plus, Delete } from '@element-plus/icons-vue'
import { SPUSTATUS } from '../../index.vue'
import { ref, onMounted ,nextTick,computed} from 'vue'
import { ElMessage, type InputInstance, type UploadProps, type UploadUserFile } from 'element-plus'
import trademarkApi, { type TrademarkListModel } from '@/api/trademark';
import spuApi, { type BaseSaleListModel, type SpuImageListModel, type SpuModel, type SpuSaleAttrListModel ,type SpuSaleAttrModel} from '@/api/spu';
import { useCategoryStore } from '@/stores/category';
import { cloneDeep } from 'lodash';
const categoryStore=useCategoryStore();
const props = defineProps<{
   spuInfo: SpuModel,
}>()
// const emits = defineEmits(['update:modelValue']);
const emits = defineEmits(['update:modelValue','spuInfo']);

// 图片列表
const dialogVisible = ref(false); 
const dialogImageUrl = ref(''); 

//方法一
// const handlerSuccess: UploadProps['onSuccess'] = (response, uploadFile,uploadFiles) => {
//   // console.log(response, uploadFile,uploadFiles);
//   spuImageList.value=uploadFiles as any;
//    spuImageList.value?.forEach(item=>{
//       item.url=item.response.data;
//       item.imgUrl=item.url as string;
//       item.imgName=item.name as string;
//    });
//   //  console.log(spuImageList.value)
// }
const handlerSuccess: UploadProps['onSuccess'] = (response, uploadFile,uploadFiles) => {
  // console.log(response, uploadFile,uploadFiles);
  const tmpImgList:SpuImageListModel=[];
  uploadFiles.forEach(item=>{
    //  tmpImgList.push({
    //     imgName: item.name,
    //     imgUrl: (item.response as any).data,
    //     // 注意:upload组件预览图片的时需要url和name这两个属性的
    //     name: item.name,
    //     url: (item.response as any).data,
    //     response: item.response 
    // })
    if(item.response){
      tmpImgList.push({
        imgName: item.name,
        imgUrl: (item.response as any).data,
        name: item.name,
        url: (item.response as any).data,
        response: item.response 
    })
    }else{
      tmpImgList.push(item as any)
    }
  })
  spuImageList.value=tmpImgList;
}


const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  // console.log(uploadFile, uploadFiles)
  spuImageList.value=uploadFiles as any;
}

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}





// 取消
const cancelSave = () => {
  emits('update:modelValue', SPUSTATUS.SPULIST);
  emits('spuInfo')
}


// 品牌下拉
const trademarkList = ref<TrademarkListModel>();
const getTrademarkList = async () => {
  try {
    let result = await trademarkApi.getList();

    trademarkList.value = result;
  } catch (error) {
    console.error(error);
    ElMessage.error('获取品牌下拉数据失败');
  }
}
// 获取销售属性
const baseSaleAttrList = ref<BaseSaleListModel>()
const getBaseSaleAttrList = async () => {
  try {
    let result = await spuApi.getSaleAttrList();
    baseSaleAttrList.value = result;
  } catch (error) {
    console.error(error);
    ElMessage.error('获取销售属性下拉数据失败');
  }
}
// 获取当前spu的图片
const spuImageList = ref<SpuImageListModel>()
const getSpuImageList = async () => {
  try {
    let result = await spuApi.getSpuImageList(spuForm.value.id as number);
    // spuImageList.value = result;
    // console.log('spuImageList', spuImageList.value)
    spuImageList.value=result.map(item=>{
       return {
        ...item,
        name: item.imgName,
        url: item.imgUrl 
      }
    })
  } catch (error) {
    console.error(error);
    ElMessage.error('获取SPU的图片列表失败');
  }
}
// spu的销售属性列表
// const spuSaleAttrList = ref<SpuSaleAttrListModel>()
const getSpuSaleAttrList = async () => {
  try {
    let result = await spuApi.getSpuSaleAttrList(spuForm.value.id as number);
    // spuSaleAttrList.value = result;
    spuForm.value.spuSaleAttrList=result;
    // console.log('spuSaleAttrList', spuSaleAttrList.value)
  } catch (error) {
    console.error(error);
    ElMessage.error('获取SPU的销售属性列表失败');
  }
}



const initData = async() => {
  // if (spuForm.value.id) { 
  //   getSpuImageList(); 
  //   getSpuSaleAttrList(); 
  // }
  if(props.spuInfo.id){
    spuForm.value=cloneDeep(props.spuInfo)
    await getSpuImageList(); 
    await getSpuSaleAttrList(); 
  }
  await getTrademarkList(); 
  await getBaseSaleAttrList(); 
}

onMounted(() => {
  initData();
});


// 交互
//新增
const initSpuForm=()=>({
  spuName:'', 
  description:'', 
  category3Id: undefined, 
  tmId:undefined, 
  spuSaleAttrList: [], 
  spuImageList:[]  
});
const spuForm=ref<SpuModel>(initSpuForm());
// const spuForm = props.spuInfo; 

//销售属性的手机
    //获得value"`${bsa.id}:${bsa.name}`
const attrIdAttrVal =ref('')
const addSaleAttr=()=>{
  if(!attrIdAttrVal.value) return;
  const [ baseSaleAttrId, saleAttrName] =attrIdAttrVal.value.split(':');
  spuForm.value.spuSaleAttrList.push({
    baseSaleAttrId:Number(baseSaleAttrId),
    saleAttrName,
    spuSaleAttrValueList:[]
  });
    //下拉框清楚已经选择的属性
    attrIdAttrVal.value='';
};
    //过滤掉已经出现下拉框中的属性=>不把展示的销售属性列表写死
    // baseSaleAttrList -> 原始数据
    // saleAttrList 过滤后的数据
  const saleAttrList=computed(()=>{
    return baseSaleAttrList.value?.filter(item => {
    const isRepeate = spuForm.value.spuSaleAttrList.some(row => {
      return row.saleAttrName == item.name
    })
    return !isRepeate;
  })
  });

  //销售属性值的展示与添加 
  //不能单独使用变量 需要定义在内部
  // const inputVisible=ref(false)
  // const inputValue=ref('')
  //点击输入框
  const handleInputConfirm=(row:SpuSaleAttrModel)=>{
    if(!row.inputValue){
      row.inputVisible=false;
       return;
    }else{
      const isRepeat=row.spuSaleAttrValueList.map(item=>item.saleAttrValueName).includes(row.inputValue);
      if(isRepeat){
        row.inputValue='';
        row.inputVisible=false;
        ElMessage.error("请不要重复属性值")
        return;
      }
      row.spuSaleAttrValueList.push({
          baseSaleAttrId: row.baseSaleAttrId, 
          saleAttrValueName: row.inputValue, 
      });
        row.inputValue='';
        row.inputVisible=false;
    }
    
  }
  //点击新增按钮
  const InputRef=ref<InputInstance>()
  const showInput=(row:SpuSaleAttrModel)=>{
    row.inputVisible=true;
    nextTick(()=>{
      InputRef.value?.focus();
    })
  }


  //点击保存按钮 获取数据 发送请求
  const onSave=async ()=>{
    (spuForm.value as any).spuImageList=(spuImageList.value  as SpuImageListModel).map(item =>{
      // return {
      //   imgName: item.imgName, 
      //   imgUrl: item.imgUrl, 
      // }
      if(item.id){
        return item;
      }else{
        return {
        imgName: item.imgName, 
        imgUrl: item.imgUrl, 
      }
      }
    });
    spuForm.value.spuSaleAttrList.forEach(item=>{
      delete item.inputValue;
      delete item.inputVisible
    });
    if(!spuForm.value.category3Id){
        spuForm.value.category3Id=categoryStore.category3Id;
    };
    console.log("spuForm",spuForm.value);

    //校验
    const {spuName, description, category3Id, tmId, spuSaleAttrList ,spuImageList:imgList} =spuForm.value;
     if ( !(spuName && tmId && category3Id && imgList.length && spuSaleAttrList.length) ) {
    ElMessage.error('名称、品牌、图片列表、销售属性列表为必填项,请检查')
    return;
  }
    //发送请求
    try{
      let result=await spuApi.saveSpu(spuForm.value);
      ElMessage.success("保存成功");
      cancelSave();
    }catch(err){
      console.log(err);
      ElMessage.error("保存失败")
    }
  }
</script>

<style scoped>
</style>